package com.juku2024.juku.tools

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.network.api.Api
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.Executors

object DownloadApkTools {

    fun downloadApk(url: String, progress: (t: Int) -> Unit, success: () -> Unit, error: () -> Unit) {
        val file = File(BaseApplication.context.getExternalFilesDir("Apk"), "update.apk")
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        val retrofit = Retrofit.Builder()
            .baseUrl("http://ctaid.newtvmedia.link/") //base的网络地址
            .callbackExecutor(Executors.newSingleThreadExecutor()) //设置线程,如果不设置下载在读取流的时候就会报错
            .build()
        val httpList = retrofit.create(Api::class.java)
        val call: Call<ResponseBody> = httpList.downloadApk(url) //下载地址  太长了所以我用DOWNLOAD_URL_PATH封装了一下,不要误解
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    val body = response.body()
                    if (body == null) {
                        LogC.e("下载 -> body is  null")
                        return
                    }
                    val total = body.contentLength()
                    var current = 0
                    val inputStream = body.byteStream()
                    val fileOutputStream = FileOutputStream(file)

                    val bytes = ByteArray(2048)
                    var len = -1
                    while (((inputStream.read(bytes)).also { len = it }) != -1) {
                        fileOutputStream.write(bytes, 0, len)
                        fileOutputStream.flush()
                        current += len

                        val percent = ((current * 1f / total) * 100).toInt()
                        LogC.d("下载 -> apk下载比例：$percent")
                        progress(percent)
                    }
                    success()
                    fileOutputStream.flush()
                    fileOutputStream.close()
                    inputStream.close()
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                    error()
                } catch (e: IOException) {
                    e.printStackTrace()
                    error()
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                LogC.e("下载 -> 出错 " + t.message)
                error()
            }
        });

    }


    fun install(activity: AppCompatActivity) {
        val isInstallPermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            BaseApplication.context.packageManager.canRequestPackageInstalls()
        } else {
            true
        }
        if (!isInstallPermission) {
            LogC.e("下载 -> 申请权限....")
            //权限没有打开则提示用户去手动打开
            openInstallPermission(activity)
            return
        }
        LogC.e("下载 -> 继续安装....")
        installApk(activity)
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    private fun openInstallPermission(activity: AppCompatActivity) {
        val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + BaseApplication.context.packageName))
        } else {
            Intent(Settings.ACTION_SECURITY_SETTINGS, Uri.parse("package:" + BaseApplication.context.packageName))
        }
        val register = activity.activityResultRegistry.register("test1", ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                installApk(activity)
            } else {

            }
            LogC.e("下载 -> 从设置页面返回了...." + it.resultCode)
        }

        //启动Activity
        register.launch(intent)
    }

    /**
     * 安装APK
     * @param activity 上下文
     */
    private fun installApk(activity: AppCompatActivity) {
        val intent = Intent(Intent.ACTION_VIEW)
        val file = File(BaseApplication.context.getExternalFilesDir("Apk"), "update.apk")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //这里要注意FileProvider一定要在AndroidManifest中去声明哦
            //同时com.mc.mcplatform代表你自己的包名
            val apkUri = FileProvider.getUriForFile(activity, activity.packageName + ".fileprovider", file)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val uri = Uri.fromFile(file)
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
        }
        activity.startActivity(intent)
    }



    fun downloadApk(activity: AppCompatActivity, url: String) {
        val file = File(BaseApplication.context.getExternalFilesDir("Apk"), "update.apk")
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        val retrofit = Retrofit.Builder()
            .baseUrl("http://ctaid.newtvmedia.link/") //base的网络地址
            .callbackExecutor(Executors.newSingleThreadExecutor()) //设置线程,如果不设置下载在读取流的时候就会报错
            .build()
        val httpList = retrofit.create(Api::class.java)
        val call: Call<ResponseBody> = httpList.downloadApk(url) //下载地址  太长了所以我用DOWNLOAD_URL_PATH封装了一下,不要误解
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                try {
                    val body = response.body()
                    if (body == null) {
                        LogC.e("下载 -> body is  null")
                        return
                    }
                    var current = 0
                    val inputStream = body.byteStream()
                    val fileOutputStream = FileOutputStream(file)

                    val bytes = ByteArray(2048)
                    var len = -1
                    while (((inputStream.read(bytes)).also { len = it }) != -1) {
                        fileOutputStream.write(bytes, 0, len)
                        fileOutputStream.flush()
                        current += len
                    }

                    fileOutputStream.flush()
                    fileOutputStream.close()
                    inputStream.close()

                    install(activity)

                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                } catch (e: IOException) {
                    e.printStackTrace()

                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                LogC.e("下载 -> 出错 " + t.message)
            }
        });

    }

}